﻿//-----------------------------------------------------------------------
// <copyright company="Microsoft Corporation">
//     Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Microsoft.DevDiv.Wpf.Samples
{
    using System;
    using System.Net;
    using System.Threading;
    using System.Xml;
    using System.Xml.XPath;

    public class LiveSearchService
    {
        public LiveSearchService(string appId)
        {
            this.appId = appId;
        }

        public event EventHandler<WebRequestEventArgs> WebRequestCreated;

        public void BeginSearch(
            LiveSearchImageSearchOptions options,
            Action<LiveSearchResult> completedCallback)
        {
            WaitCallback threadPoolCallback =
                (x) =>
                {
                    WebRequest webRequest = WebRequest.Create(BuildQueryString(options));

                    OnWebRequestCreated(new WebRequestEventArgs(webRequest));

                    AsyncCallback getResponseCallback = (asyncResult) =>
                    {
                        OnGetResponse(webRequest.EndGetResponse(asyncResult), completedCallback);
                    };

                    webRequest.BeginGetResponse(getResponseCallback, null);
                };

            ThreadPool.QueueUserWorkItem(threadPoolCallback);
        }

        protected virtual void OnWebRequestCreated(WebRequestEventArgs e)
        {
            EventHandler<WebRequestEventArgs> handler = this.WebRequestCreated;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        private static void OnGetResponse(
            WebResponse response,
            Action<LiveSearchResult> completedCallback)
        {
            XPathDocument document = new XPathDocument(response.GetResponseStream());
            XPathNavigator navigator = document.CreateNavigator();
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(navigator.NameTable);
            nsmgr.AddNamespace("api", "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element");
            nsmgr.AddNamespace("mms", "http://schemas.microsoft.com/LiveSearch/2008/04/XML/multimedia");

            XPathNavigator searchResponseNode = navigator.SelectSingleNode("/api:SearchResponse", nsmgr);
            LiveSearchResult searchResponse = LiveSearchResult.Create(new LiveSearchXmlObject(searchResponseNode, nsmgr));
            completedCallback(searchResponse);
        }

        private string BuildQueryString(LiveSearchImageSearchOptions request)
        {
            return "http://api.bing.net/xml.aspx?"

                 // Common request fields (required)
                 + "AppId=" + this.appId
                 + "&Query=" + request.Query
                 + "&Sources=Image"

                 // Common request fields (optional)
                 + "&Version=2.0"
                 + "&Adult=Moderate"

                 // Image-specific request fields (optional)
                 + "&Image.Count=" + request.Count
                 + "&Image.Offset=" + request.Offset;
        }

        private readonly string appId;
    }
}